﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using AutoMapper;
using FikriKibar.Common.Helpers;
using FikriKibar.DataAccess.Abstract;
using FikriKibar.DataAccess.ContextBase;
using FikriKibar.DataAccess.RepositoryBase;
using FikriKibar.Entities.Concrete;

namespace FikriKibar.DataAccess
{
    public class EfFileDal : EfEntityRepositoryBase<File, FikriKibarDbContext>, IFileDal
    {
        protected override File AddEntity(File entity, FikriKibarDbContext context)
        {
            return context.Files.Add(entity);
        }

        protected override File UpdateEntity(File entity, FikriKibarDbContext context)
        {
            var oldEntity = GetEntity(entity, context);
            var newEntity = Mapper.Map(entity, oldEntity);
            context.Entry(oldEntity).CurrentValues.SetValues(newEntity);
            return newEntity;
        }

        protected override List<File> GetEntities(FikriKibarDbContext context)
        {
            return context.Files.Include(e=>e.User_CreatedBy).Include(e=>e.User_UpdatedBy).ToList();
        }

        protected override List<File> FilterEntities(FikriKibarDbContext context, Expression<Func<File, bool>> where)
        {
            return context.Files.Include(e=>e.User_CreatedBy).Include(e=>e.User_UpdatedBy).Where(where).ToList();
        }

        protected override List<File> FilterEntities(FikriKibarDbContext context, Expression<Func<File, bool>> where, SortHelper<File> sortHelper)
        {
            var query = (IOrderedQueryable<File>)context.Files.Include(e=>e.User_CreatedBy).Include(e=>e.User_UpdatedBy).Where(where);
            query = sortHelper.GenerateOrderedQuery(query);
            return query.ToList();
        }


        protected override List<File> FilterEntities(FikriKibarDbContext context, Expression<Func<File, bool>> where, SortHelper<File> sortHelper, int index, int size)
        {
            var query = (IOrderedQueryable<File>)context.Files.Include(e=>e.User_CreatedBy).Include(e=>e.User_UpdatedBy).Where(where);
            query = sortHelper.GenerateOrderedQuery(query);
            return query.Skip((index - 1) * size).Take(size).ToList();
        }

        protected override File GetEntity(File entity, FikriKibarDbContext context)
        {
            return context.Files.Include(e=>e.User_CreatedBy).Include(e=>e.User_UpdatedBy).FirstOrDefault(e => e.Id == entity.Id);
        }

        public File GetById(int fileId)
        {
            using (var context = new FikriKibarDbContext())
            {
                return context.Files.Include(e=>e.User_CreatedBy).Include(e=>e.User_UpdatedBy).FirstOrDefault(e => e.Id == fileId);
            }
        }


    }
}
